//
// Created by fazhehy on 2024/7/2.
//

#include "bldc_adc.h"

float offset_ia = 0;
float offset_ib = 0;
float offset_ic = 0;

void bldc_adc_init()
{
    // A
    adc_init(ADC0_CH00_P06_0, ADC_12BIT);
    // B
    adc_init(ADC0_CH01_P06_1, ADC_12BIT);
    // C
    adc_init(ADC0_CH02_P06_2, ADC_12BIT);

//    for (int i = 0; i < 1000; ++i) {
//        offset_ia += adc_convert(ADC0_CH00_P06_0)*3.3/4095;
//        offset_ib += adc_convert(ADC0_CH01_P06_1)*3.3/4095;
//        offset_ic += adc_convert(ADC0_CH02_P06_2)*3.3/4095;
//    }
//    offset_ia /= 1000;
//    offset_ib /= 1000;
//    offset_ic /= 1000;
    adc_mean_filter_convert(ADC0_CH00_P06_0, 10);
    adc_mean_filter_convert(ADC0_CH01_P06_1, 10);
    adc_mean_filter_convert(ADC0_CH02_P06_2, 10);
}

static uint32_t i = 0;
float adc_value_a_phase_max_temp = 0;
float adc_value_a_phase_max = 0;
float adc_value_b_phase_max_temp = 0;
float adc_value_b_phase_max = 0;
float adc_value_c_phase_max_temp = 0;
float adc_value_c_phase_max = 0;
float adc_value_a_phase = 0;
float adc_value_b_phase = 0;
float adc_value_c_phase = 0;

void bldc_adc_read()
{
    adc_value_a_phase = (float )adc_convert(ADC0_CH00_P06_0)*3.3f/4095 - offset_ia;
    adc_value_b_phase = (float )adc_convert(ADC0_CH01_P06_1)*3.3f/4095 - offset_ib;
    adc_value_c_phase = (float )adc_convert(ADC0_CH02_P06_2)*3.3f/4095 - offset_ic;
//    adc_value_a_phase *= 1/(50*0.001f);
//    adc_value_b_phase *= 1/(50*0.001f);
//    adc_value_c_phase *= 1/(50*0.001f);
    i ++;

    if (i <= 32){
        if (adc_value_a_phase_max_temp < adc_value_a_phase)
            adc_value_a_phase_max_temp = adc_value_a_phase;
        if (adc_value_b_phase_max_temp < adc_value_b_phase)
            adc_value_b_phase_max_temp = adc_value_b_phase;
        if (adc_value_c_phase_max_temp < adc_value_c_phase)
            adc_value_c_phase_max_temp = adc_value_c_phase;
    }
    else{
        adc_value_a_phase_max = 0.1f*adc_value_a_phase_max_temp + 0.9f*adc_value_a_phase_max;
        adc_value_a_phase_max_temp = 0;
        adc_value_b_phase_max = 0.1f*adc_value_b_phase_max_temp + 0.9f*adc_value_b_phase_max;
        adc_value_b_phase_max_temp = 0;
        adc_value_c_phase_max = 0.1f*adc_value_c_phase_max_temp + 0.9f*adc_value_c_phase_max;
        adc_value_c_phase_max_temp = 0;
        i = 0;
    }

    if ((adc_value_a_phase_max+adc_value_b_phase_max+adc_value_c_phase_max >= max_current) && stop_flag_flag)
        stop_flag = true;
//    vofa_send_data(adc_value_a_phase);
//    vofa_send_data(adc_value_b_phase);
//    vofa_send_data(adc_value_c_phase);
//    vofa_send_data(adc_value_a_phase_max+adc_value_b_phase_max+adc_value_c_phase_max);
//    vofa_send();

//    printf("%d, %d, %d\n", adc_value_a_phase, adc_value_b_phase, adc_value_c_phase);
}
